<template>
  <div class="login">
    <div>
      <h1 class="welcome">麦阿尼翻译</h1>
      <h4 class="subTitle">强大的中/阿翻译语言模型，祝你创造无限可能！</h4>
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <div class="titleTab">
          <span v-for="tab in logintypeList" :key="tab.type" class="tabItem" :class="{active: loginType==tab.type}" @click="logintypeClick(tab)">{{ tab.name }}</span>
        </div>
        
        <el-form-item v-if="loginType==1" prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入邮箱"
          >
            <template #prefix> <span style="padding-right:15px;">{{ $t('login.email') }}</span></template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="loginType==1" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
          >
            <template #prefix> <span style="padding-right:15px;">{{ $t('login.password') }}</span></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="loginForm.code"
            size="large"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter="handleLogin"
          >
            <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
        <el-form-item v-show="loginType==2" style="width:100%;">
          <div id="login_container" class="ewm"></div>
        </el-form-item>

        <el-form-item style="width:100%;">
          <el-radio v-model="agreeLogin" :label="1">登录即代表你同意<span class="link" @click="agreeVisible=true;agreeType=1">《用户服务条款》</span>及<span class="link" @click="agreeVisible=true;agreeType=2">《用户隐私政策》</span></el-radio>
        </el-form-item>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="large" type="primary"
            style="width:100%;"
            @click.prevent="handleLogin"
          >
            <span v-if="!loading">{{ $t('login.login') }}</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div class="register" style="float: right;" v-if="register&&loginType==1">
            <router-link class="link-type" :to="'/login'">忘记密码</router-link>
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
      <div style="margin-top: 16px;">
        <div class="lofinTip">
          请放心，进来就不会有任何人类认知可以解释的奇怪事情发生
        </div>
      </div>
      
    </div>
    <el-dialog v-model="agreeVisible" :title="agreeType == 1?'用户服务条款':'用户隐私协议'" width="55%" >
      <div class="agreeText" style="max-height: 60vh;overflow: auto;">
        <pre style="white-space: pre-wrap">
          {{ agreeType == 1 ? service : privacy }}
        </pre>
      </div>
    </el-dialog>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2023 chatvip, Inc </span>
    </div>
  </div>
</template>

<script setup>
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import { ElMessage } from "element-plus";
import { service, privacy } from "../utils/loginterm";
import { getQueryObject } from "@/utils";
import { getCurrentInstance, reactive, ref } from "vue"
import { useRouter } from "vue-router";

const queryData = getQueryObject() || {}

const userStore = useUserStore()
const router = useRouter();
const { proxy } = getCurrentInstance();
const share_id = sessionStorage.getItem('share_id')
sessionStorage.removeItem('share_id')

if (queryData.code) {
  // 调用action的登录方法
  userStore.wxlogin({code: queryData.code, state: queryData.state}).then(() => {
        window.postMessage({ type: "wxlogin", status: true }, "*");
        router.push({ path: redirect.value || "/" });
      }).catch(() => {
        
      });
}

window.addEventListener("message", (event) => {
  if (event.data.type == "wxlogin") {
    if (event.data.status) {
      router.push({ path: redirect.value || "/" });
    } else {
      ElMessage.error("微信登录失败");
    }
  }
}, false);

let loginType = ref(1)
const logintypeList = reactive([
  { name: '邮箱登录', type: 1 },
  { name: '微信登录', type: 2 },
])
const agreeLogin = ref(1)

const loginForm = ref({
  username: "user@user.com",
  password: "qwer",
  rememberMe: false,
  code: "",
  uuid: ""
});

const logintypeClick = (item) => {
  loginType.value = item.type
  agreeLogin.value = 0
  if (item.type == 2) {
    getWXCode()
    agreeLogin.value = 1
  }
}
setTimeout(() => {
  logintypeClick(logintypeList[0])
}, 1000)

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的邮箱" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }]
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(false);
// 注册开关
const register = ref(true);
const redirect = ref(undefined);

function handleLogin() {
  if (loginType.value == 2 ) {
    router.push({ path: "/" });
    return
  }
  if (!agreeLogin.value) {
    ElMessage.error('请同意用户协议')
    return
  }
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("username");
        Cookies.remove("password");
        Cookies.remove("rememberMe");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        router.push({ path: redirect.value || "/" });
      }).catch((err) => {
        loading.value = false;
        ElMessage.error(err.message || '登录失败')
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
}

const agreeVisible = ref(false)
const agreeType = ref(1)

function getCode() {
  // getCodeImg().then(res => {
  //   captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
  //   if (captchaEnabled.value) {
  //     codeUrl.value = "data:image/gif;base64," + res.img;
  //     loginForm.value.uuid = res.uuid;
  //   }
  // });
}

function getCookie() {
  // const username = Cookies.get("username");
  // const password = Cookies.get("password");
  // const rememberMe = Cookies.get("rememberMe");
  // loginForm.value = {
  //   username: username === undefined ? loginForm.value.username : username,
  //   password: password === undefined ? loginForm.value.password : decrypt(password),
  //   rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  // };
}

function getWXCode() {
  const url = encodeURIComponent(location.href) 
  // const url = encodeURIComponent('http://chatpc.majh.top/login')
  // const url = encodeURIComponent('https://chatvip.com.cn/guyu/gy_chat_web/users/wx_auth2')
  var obj = new WxLogin({
      self_redirect: false,
      id:"login_container", 
      appid: "wx792b9edf2d5c0a1d", 
      scope: "snsapi_login", 
      redirect_uri: url,
      state: share_id ? `share_id_${share_id}` : new Date().getTime(),
      style: "",
      href: ""
    });
}

getCode();
getCookie();

</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: linear-gradient(to right bottom, rgba(179, 212, 255, 1) 0%, rgb(245,245,245) 40%);
}

.welcome {
  color: #222;
  text-align: center;
  margin-bottom: 6px;
}
.subTitle {
  color: #222;
  text-align: center;
  margin: 0px 0 26px 0;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}
.titleTab {
  display: flex;
  // justify-content: center;
  align-items: center;
  width: 100%;
  height: 60px;
  color: rgb(79,79,79);
  .tabItem {
    text-align: center;
    cursor: pointer;
    padding: 0 15px;
    &.active {
      color: #000;
    }
    &:first-child {
      border-right: 2px solid #ccc;
    }
  }
}

.register {
  display: flex;
  justify-content: space-between;
  width: 100%;
  > * {
    color: #409eff;
  }
}

:deep .el-input__prefix {
  color: #444;
}

.login :deep .el-radio {
  color: #888;
}

span.link {
  // color: rgba(0, 186, 173, 1);
  cursor: pointer;
}

.ewm {
  width: 300px;
  height: 400px;
  margin: 0 auto;
  background: #fff;
}

.lofinTip {
  text-align: center;
  color: rgb(173,173,173);
  border: 1px solid rgb(219,219,219);
  font-size: 12px;
  margin-top: 10px;
  border-radius: 15px;
  padding: 6px 15px;
  width: 400px;
  margin: 0 auto;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 480px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}

:deep .el-input__inner {
  color: #000;
}

</style>
<style lang="scss">
.darkDialog {
  background: rgb(64,64,64);
  .el-dialog__title, .el-dialog__headerbtn .el-dialog__close {
    color: #fff;
  }
  .el-dialog__body {
    padding: 20px 30px;
  }
  .el-dialog__footer {
    border-top: 1px solid #fff;
  }
  .agreeText {
    color: #fff;
    max-height: 75vh;
    overflow: auto;
  }
}
</style>